package com.qk.management.web.interceptor;

import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * &#064;author：zzq
 * &#064;createTime：2025/10/11 14:53
 * &#064;description：
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final String TOKEN_HEADER_NAME = "token";

    /**
     * 拦截器方法
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器对象
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        //获取请求头中的token
        String token = request.getHeader(TOKEN_HEADER_NAME);
        //校验token
        if (Objects.isNull(token)) {
            log.info("token为空");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //解析token
        log.info("token:{}", token);
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("token解析成功");
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            log.info("用户id:{}", id);
            log.info("用户名称:{}", username);
            //将用户id存入threadlocal
            CurrentUserContextHolders.set(id);
            return true;
        } catch (Exception e) {
            log.error("token解析失败", e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
